<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html debug="true">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    <meta http-equiv="Pragma" content="no-cache">

    <link rel="stylesheet" href="css/index.css?update=1"/>

    <script src="js/jquery-1.11.0.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jquery-ui-1.10.3.custom.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript" charset="utf-8"></script>
    <%--<script src="js/jqgrid/js/i18n/grid.locale-${locale}.js" type="text/javascript" charset="utf-8"></script>--%>
    <script src="js/ckeditor/ckeditor.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/ckeditor/adapters/jquery.js" type="text/javascript" charset="utf-8"></script>


    <script src="js/jquery.msgBox.v1.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jsfileuploader/jquery.fileupload.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jsfileuploader/jquery.iframe-transport.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jquery-loadTemplate/jquery.loadTemplate-1.1.0.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jquery.blockUI.min.js" type="text/javascript" charset="utf-8"></script>

    <!--[if lt IE 9]>
    <script src="js/json2.js" type="text/javascript" charset="utf-8"></script>
    <![endif]-->

    <%--<script src="js/firebug-lite.js" type="text/javascript" charset="utf-8"></script>--%>


    <script src="js/util.js" type="text/javascript" charset="utf-8"></script>


    <style type="text/css">
        .no-close .ui-dialog-titlebar-close {
            display: none;
        }

        td.label {
            text-align: left;
            vertical-align: middle;
            font-weight: bold;
            padding-right: 10px;
            width: 120px;
        }

        #tabs li .ui-icon-close {
            float: left;
            margin: 0.4em 0.2em 0 0;
            cursor: pointer;
        }

        .copyListSearchResult {
            width: 100%;
            height: 100%;
        }

    </style>


    <script type="text/html" id="tabTemplate">
        <a data-template-bind='[{"attribute": "href", "value": "id"}, {"attribute": "content", "value": "title"}]'></a>
        <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span>
    </script>

    <script>
        if (typeof console == "undefined" || console == null) {
            console = {
                log: function () {
                }
            }
        }
        var global = {
            NEW_REQUEST_TAB_ID: 'ospNewRequestTab'
        };

        $.extend(global, <s:property value="globalObjects" escape="false" />);

        $(function ($) {
            $("#logout").button();
            $('span.ui-button-text', '#logout').css({padding: '.1em 1em'});

            /**
             * add new tab
             * @param title new tab title
             * @param panel new tab panel, this panel id must be tab title
             * */
            function addTab(title, panel) {
                var model = {
                    id: '#' + panel.attr('id'),
                    title: title
                };
                if (!model.id)return;

                var li = $("<li>").loadTemplate($("#tabTemplate"), model).get(0);

                tabs.find(".ui-tabs-nav").append(li);
                tabs.append(panel);
                tabs.tabs("refresh");
            }

            global.autoResizeGrid = function (panel) {
                var innerGrid = $('table.ui-jqgrid-btable', panel);
                var resizeGrids = ['requestGrid', 'followupGrid'];
                var offsetHeight = 100;
                if (innerGrid && -1 != $.inArray(innerGrid.attr('id'), resizeGrids)) {
//            var parentTd =innerGrid.parents("td[class$='parent']");
//            console.log("Adjust inner grid %s size =[%d, %d].", innerGrid.attr('id'), panel.height(), panel.width());
                    if (innerGrid.attr('id') == 'requestGrid')  offsetHeight = 126;
                    innerGrid.setGridHeight(panel.height() - offsetHeight).setGridWidth(panel.width() - 10);
                }
            }

            var tabs = $("#tabs").tabs({
//            collapsible: true,
                activate: function (event, ui) {
                    var tabsIndexMap = {"requests": 0, "followUps": 1};
                    //current activated tabIndex
//            tabs.data("currentActivatedTabIndex", tabsIndexMap[ui.newTab.attr("aria-controls")]);
                    global.autoResizeGrid(ui.newPanel);
                },
                create: function (event, ui) {
//            global.autoResizeGrid(ui.panel);
                }
            });

            /**
             * @parm tadId
             * whether tab is opened.
             * return the opened tab if it is opened
             * */
            global.isTabOpened = function (tabId) {
                var tabItem = null;
                var newRequestTabOpened = $('#tabs .ui-tabs-nav > li').map(function (idx, elem) {
                            if ($(elem).attr('aria-controls') == tabId) {
                                tabs.tabs("option", "active", idx);
                                tabItem = $(elem);
                                return idx;
                            }
                        }).length > 0;

                if (newRequestTabOpened) {
                    console.log("tab " + tabId + " opened already.");
                }
                return tabItem;
            }

            /**
             * View request in new tablet
             * @ title tab title
             * @ requestId request id
             * @ viewModel indicate whether request displayed in request or followup model.
             * */
            global.viewRequestInTab = function (requestId, viewMode) {

                // open new tab
                var propMode = {};
                propMode[global.VIEW_MODE.FOLLOWUP] = 'attachments';
                propMode[global.VIEW_MODE.REQUEST] = 'attachments';

                var postData = {
                    id: requestId,
                    viewMode: viewMode,
                    prop: propMode[viewMode]
                };

                $.blockUI();
                var divId = 'tab_' + requestId;
                var panel = $("<div id='" + divId + "'>").load('view-request', postData, function (page) {
                    $.unblockUI();
                    var reqNo = $('#reqNo', this).val();
                    var tabIndex = viewMode == global.VIEW_MODE.EMAIL ? tabs.data("currentActivatedTabIndex") : viewMode - 1;
                    panel.data("openFromTabIndex", tabIndex);
                    addTab(reqNo, panel);
                    tabs.tabs("option", "active", ($('div.ui-tabs-panel', tabs).length - 1));
                });
            }

            <s:if test="#parameters.requestId != null && #parameters.viewMode != null">
            global.viewRequestInTab(<s:property value="#parameters.requestId" />, <s:property value="#parameters.viewMode" />);
            </s:if>


            /**
             * Create new request in tab
             * */
            global.createNewRequest = function (category, title, newTabId) {
                var newTabId = newTabId || global.NEW_REQUEST_TAB_ID;
                var title = title || 'New Request'
                if (global.isTabOpened(newTabId))return;

                $.blockUI();
                var panel = $("<div id='" + newTabId + "'>").load('create-new-request', {category: category}, function (page) {
                    $.unblockUI();
                    addTab(title, panel);
                    panel.data("openFromTabIndex", 0);
                    tabs.tabs("option", "active", ($('div.ui-tabs-panel', tabs).length - 1));
                });
            }

            /**
             * Close tab which id is tabId
             * @param tabId the id of tab to be closed.
             * @param openFromTabIndex this tab open from which tab
             * */
            global.closeTab = function (tabId) {
//        console.log("tableId="+tabId);
                $("#tabs .ui-tabs-nav a").filter(function (idx, elem) {
                    var subIndex = elem.href.lastIndexOf('#');
                    return tabId == elem.href.substring(subIndex + 1);
                    var hrefId = elem.href.substring(-1 != subIndex ? subIndex + 2 : 1);
                }).next("span.ui-icon-close").click();
            }

            // close icon: removing the tab on click
            tabs.on("click", "span.ui-icon-close", function (e) {
                var panelId = $(this).closest("li").remove().attr("aria-controls");
                var panel = $("#" + panelId);
                var openFromTabIndex = panel.data("openFromTabIndex");
                panel.remove();
                tabs.tabs("refresh");

                if (openFromTabIndex != null) {
                    tabs.tabs("option", "active", openFromTabIndex);
                }
            });

            var loginDialog = $("#login");

            function login() {
                var postData = {
                    'csl': $("#csl", loginDialog).val(),
                    'password': $("#password", loginDialog).val(),
                    'rememberMe': $("#rememberMe", loginDialog).prop('checked'),
                    'timeZoneOffset': -new Date().getTimezoneOffset() * 60 * 1000
                };
//        console.log("postData=%o", postData);
                $.blockUI({message: '<h1>Signing in, please wait...</h1>'});
                var url = "login";
                url = "https://" + location.hostname + ":" + ${httpsPort} +location.pathname.substring(0, location.pathname.lastIndexOf('/') + 1) + url;
//        //with jsonp
//        url += "?callback=?";
                console.log("url=%o", url);

                $.post(url, postData, function (json) {
                    $.unblockUI();
                    if (json.status !== 0) {
                        $.msgBox(json.message, null, {
                            title: "Error"
                        });
                        return;
                    } else {  // success
                        afterLogin(postData['csl']);
                        loginDialog.dialog("close");
                    }
                });
            }

            loginDialog.dialog({
                dialogClass: "no-close",
                autoOpen: ${not login},
                closeOnEscape: false,
                modal: true,
                title: "Login",
                buttons: {
                    "Login": login
                }
            }).keypress(function (e) {
                if (e.which != 13) return;
                login();
            });

            <s:if test="#parameters.category != null">
            global.createNewRequest('<s:property value="#parameters.category"/>');
            </s:if>

            global.addCCUserDialog = $("#addCCUserDialog").dialog({
                autoOpen: false,
                width: 500,
                height: 300,
                close: function () {
                    $("#key", this).val("");
                    $("#searchedResult", this)[0].options.length = 0;
                    $(this).unblock();
                },
                create: function () {
                    var that = this;
                    $("#searchUser", this).button().click(function () {
                        var searchValues = $("#key", that).val();
                        if (!searchValues) return;
                        $(that).block({message: "retrieving..."});
                        $.post('get-users-by-key', {key: searchValues}, function (users) {
                            $(that).unblock();
//                        var options = json2Options(users, false, 'cil', 'csl');
                            var options = $(users).map(function (index, user) {
                                return newOption($.jgrid.htmlEncode($.jgrid.format("{0}\t<{1}>", user.cil, user.email)), user.csl, false);
                            }).get().join('\n');
                            var searchResult = $("#searchedResult", that);
                            searchResult[0].options.length = 0;
                            searchResult.append(options);
                        });
                    });
                },
                buttons: [
                    {
                        text: 'Add',
                        click: function () {
                            var selectedOptions = $("#searchedResult>option:selected", this);
                            var requestForm = $(this).data("requestFrom");
                            $('#copyList', requestForm).append(selectedOptions);
                            $(this).dialog("close");
                        }
                    },
                    {
                        text: 'Cancel',
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            }).keypress(function (e) {
                if (e.which != 13) return;
                $("#searchUser", this).click();
            });
        });

        function afterLogin(csl) {
            location.reload()
        }
    </script>
</head>
<body>


<div>
    <div class="ui-state-focus ui-corner-all global-header">
        <table width="100%" border="0">
            <tr>
                <td><span style="font-size:18px;font-weight:bold;">
                    <s:text name="title"/></span>
                </td>
                <td align="right">
                    <s:text name="welcome"/>
                    <span style="color:#800080;font-weight:bold">
                        ${user_context.user.cil}
                    </span>&nbsp;
                    <a id="logout" href="logout"><s:text name="logout"/></a>
                </td>
                <td style="width: 20px"></td>
            </tr>
        </table>
    </div>

</div>


<div id="tabs" class="main-tabs">
    <s:if test="#session.user_context.user != null">
        <s:set scope="action" var="showFollowup"
               value="not #session.user_context.user.categories.empty or #session.user_context.user.superUser"/>
        <ul>
            <li><a href="#requests"><s:text name="myRequests"/></a></li>
            <s:if test="#showFollowup">
                <li><a href="#followUps"><s:text name="myFollowUp"/></a></li>
            </s:if>
        </ul>

        <div id="requests">
            <%@include file="myrequests.jsp" %>
        </div>

        <s:if test="#showFollowup">
            <div id="followUps">
                <%@include file="myfollowups.jsp" %>
            </div>
        </s:if>
    </s:if>
</div>

<div id="login">
    <table border="0" style="width: 100%">
        <tr>
            <td class="label"><s:text name="login.csl"/></td>
            <td><input type="text" id="csl"/></td>
        </tr>
        <tr>
            <td class="label"><s:text name="login.pwd"/></td>
            <td><input type="password" id="password"/></td>
        </tr>
        <tr>
            <td class="label" colspan="2"><s:text name="login.rememberMe"/>&nbsp;
                <input style="width: 13px" type="checkbox" checked="checked" value="true" id="rememberMe"/>
            </td>
        </tr>
    </table>
</div>


<div id="addCCUserDialog" title="Add copy list user">
    <table width="100%" height="100%" border="0">
        <tr style="height: 20px">
            <td><s:text name="searchKey"/></td>
            <td><input id="key"/></td>
            <td>
                <button id="searchUser">search</button>
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <s:select list="{}" cssClass="copyListSearchResult" theme="simple" name="searchedResult"
                          id="searchedResult" multiple="true"/>
            </td>
        </tr>
    </table>
</div>

</body>
</html>